import { constantRoutes } from '@/router'
import { getRoutesByRoleCode } from '@/api/role'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * 递归过滤异步路由表,返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    // 理论可行方案1： 再过滤前 根据菜单信息与角色的关系 对应给每个路由菜单加入可访问角色权限 再对当前登陆的角色与之判断 返回可访问的路由菜单
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 */
export function getAsyncRoutes(menuList = []) {
  const res = []
  menuList.forEach(route => { // 所有菜单都是二级结构，一级没有页面功能，所以只要添加二级菜单的路由
    if (route.hidden === '1') {
      return
    }
    if (route.children !== null) {
      const children = []
      route.children.forEach(menu => { // 二级菜单需匹配页面
        if (menu.hidden === '1') {
          console.log(menu)
          return
        }
        const url = menu.url
        children.push({
          path: menu.path,
          name: menu.path,
          key: menu.menukey,
          // 此处也可使用require
          component: resolve => require([`@/views/${url}`], resolve),
          meta: { title: menu.title, icon: menu.icon } // 菜单权限
        })
      })
      res.push({
        path: route.path,
        name: route.path,
        key: route.menukey,
        component: Layout,
        meta: { title: route.title, icon: route.icon }, // 菜单权限
        children: children
      })
    }
  })
  return res
}
const state = {
  routes: [], // 路由表集合
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, rolseCodeArrays) { // 动态生成路由
    console.log(rolseCodeArrays)
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => {
      const accessedALLRoleRoutes = [] // 可访问的路由表
      // if (roles.includes('超级管理员')) { // 超级管理员加载全部动态路由。
      //   accessedRoutes = asyncRoutes || []
      //   console.log(accessedRoutes)
      // } else { // 不是超级管理员的情况，根据对应的角色生成对应的路由并加载
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   console.log(accessedRoutes)
      // }
      const asyncRoleMenus = [] // 当前账号所拥有角色的所有菜单列表
      for (const item of rolseCodeArrays) {
        const res = await getRoutesByRoleCode(item)
        const data = res.data.main
        asyncRoleMenus.push(data)
      }
      for (let i = 0; i < asyncRoleMenus.length; i++) {
        // 根据拥有角色的菜单数据列表长度来遍历整合菜单信息
        // 生成动态路由列表
        const accessedRoleRoutes = getAsyncRoutes(asyncRoleMenus[i])
        // 添加到总动态可访问路由列表数组中
        accessedALLRoleRoutes.push(accessedRoleRoutes)
      }
      // 去重
      const originArray = accessedALLRoleRoutes[0]
      const result = []
      const obj = {}
      for (let i = 0; i < originArray.length; i++) {
        if (!obj[originArray[i].key]) {
          result.push(originArray[i])
          obj[originArray[i].key] = true
        }
      }
      commit('SET_ROUTES', result) // 把生成的路由存储起来
      resolve(result)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
